// cloudfunctions/coze-proxy/index.js - Coze API 代理云函数
const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const COZE_API_KEY = 'cztei_qc9edB4DWNu0Sqa0fFAl0vV7zjvITN9DfSDXgEIckPGN7W3tAvu4b6PjqEBb6PHtJ';
const COZE_BOT_ID = '7555475919377367075';
const COZE_API_URL = 'https://api.coze.cn/open_api/v2/chat';

exports.main = async (event, context) => {
  const { message, conversationId } = event;
  
  try {
    console.log('☁️ 云函数开始处理 Coze API 请求');
    console.log('📝 消息内容:', message);
    console.log('💬 会话ID:', conversationId);
    console.log('🔗 API URL:', COZE_API_URL);
    console.log('🆔 Bot ID:', COZE_BOT_ID);
    
    const axios = require('axios');
    
    const requestData = {
      conversation_id: conversationId || 'chat-' + Date.now(),
      bot_id: COZE_BOT_ID,
      user: 'miniprogram_user',
      query: message,
      stream: false
    };
    
    console.log('📤 发送请求数据:', JSON.stringify(requestData));
    
    const response = await axios.post(COZE_API_URL, requestData, {
      headers: {
        'Authorization': `Bearer ${COZE_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });
    
    console.log('✅ Coze API 响应成功');
    console.log('📊 响应状态码:', response.status);
    console.log('📦 响应数据:', JSON.stringify(response.data).substring(0, 500));
    
    // 检查响应中的错误码（即使HTTP状态码是200）
    if (response.data && response.data.code && response.data.code !== 0) {
      const errorMsg = response.data.msg || response.data.message || 'API返回错误';
      console.error('❌ Coze API 返回错误码:', response.data.code);
      console.error('❌ 错误信息:', errorMsg);
      
      let detailedError = errorMsg;
      if (response.data.code === 4101) {
        detailedError = 'API Key 无效，请检查云函数中的配置。错误: ' + errorMsg;
      } else if (response.data.code === 4102) {
        detailedError = 'Bot ID 无效，请检查云函数中的配置。错误: ' + errorMsg;
      }
      
      return {
        success: false,
        error: detailedError,
        code: response.data.code,
        details: response.data
      };
    }
    
    return {
      success: true,
      data: response.data
    };
    
  } catch (error) {
    console.error('❌ 云函数处理 Coze API 失败');
    console.error('🔴 错误消息:', error.message);
    console.error('🔴 错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      stack: error.stack
    });
    
    return {
      success: false,
      error: error.message || '请求失败',
      details: error.response?.data || ''
    };
  }
};
